package com.epfresh.supplier.fragment;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.entity.TagPager;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseFragment;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.LocalDisplay;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.list.LoadMoreListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.supplier.R;
import com.epfresh.supplier.activity.*;
import com.epfresh.supplier.adapter.OrderAgentAdapter;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.*;
import com.epfresh.supplier.entity.OrderDetailAgent;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zzq on 2017/9/14.
 */
public class OrderAgentFragment extends BaseFragment implements LoadMoreListView.IXListViewListener {
    //待支付 2待发货 3 待收货 4 拒签（不显示） 5退款 6 交易取消 7 交易成功 9 待评价 10减免退
    boolean typeFlag;//订单类别展示开关
    //订单列表类别 1,待支付 2,未完成,3已完成 4全部订单
    public String typeState;
    //0线上,1线下,2现场，当前暂时默认现场等同线下
    public int typeOnline;

    private LoadMoreListView lvContent;

    private List<OrderAgentList> list = new ArrayList<>();

    protected View mainView;
    protected View vException;
    protected TextView tvExceptionDescription;
    protected ImageView ivExceptionIcon;
    private ProgressBar pb;
    public int requestSucceedCount = 0;
    private int PAGE_SIZE = 5;
    OrderAgentAdapter adapter;
    Context context;
    OrderAgentActivity baseActivity;
    int postionFlag;
    TagPager tagPager = new TagPager();

    public OrderAgentFragment(String typeState){
        this.typeState = typeState;
    }
    public OrderAgentFragment(){
    }

    @Override
    public String getBaseTag() {
        return Constant.TAG_ORDER_FRAGMENT;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            typeOnline = savedInstanceState.getInt("type", 0);
        }
        return inflater.inflate(R.layout.fragment_order,
                container, false);
    }

    @Override
    public void onViewCreated(View v, Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);
        context = getContext();
        baseActivity = (OrderAgentActivity)getAppActivity();
        initHeadView(v);
        lvContent = (LoadMoreListView)v.findViewById(R.id.lv_content);

        vException = v.findViewById(R.id.v_exception);
        mainView = v.findViewById(R.id.fragment_ptr_home_ptr_frame);
        initException();
        adapter = new OrderAgentAdapter(context,lvContent, list);
        adapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View v, int position, long l) {
                Log.e("new onItemClick",""+position);

// 交货码，查看物流，取消订单，确认收货，支付， 详情
                switch (v.getId()) {
                    case R.id.ll_order:
                    case R.id.rl_more:
                    case R.id.ll_images:
/*                        Intent detail = new Intent(context, H5OrderDetailActivity.class);
                        detail.putExtra("orderId", list.get(position).getId());
                        detail.putExtra(com.epfresh.api.constant.Constant.KEY_WEB_URL, "http://m.epfresh.com/help/order_supply_new.html?orderId=" + list.get(position).getId());
                        detail.putExtra(com.epfresh.api.constant.Constant.KEY_WEB_TITLE, "订单详情");
                        startActivityForResult(detail,0x002);*/
                        break;

                    case R.id.tv_item_order_agent_goods_code:
                        requestCode(list.get(position).getId());
                        //showCodeDialog(list.get(position).getNumber());//需要单独调接口？？？？todo
                        break;
                    case R.id.ll_item_order_agent:
                        Intent detail = new Intent(context, OrderDetailAgentActivity.class);
                        detail.putExtra("id", list.get(position).getId());
                        context.startActivity(detail);
                        break;

                }
            }
        });

        lvContent.setAdapter(adapter);
        lvContent.setXListViewListener(this);
        loadData(0);
    }


    public void initException() {
        tvExceptionDescription = (TextView) vException.findViewById(R.id.tv_exception);
        ivExceptionIcon = (ImageView) vException.findViewById(R.id.iv_exception);
        pb = (ProgressBar) vException.findViewById(R.id.pb);
    }

    private PtrFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, lvContent, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    boolean refreshFlag = false;

    public void refresh() {
        if(lvContent==null)
            return;
        lvContent.resetNoMore();
        requestSucceedCount = 0;
        refreshFlag = true;
        loadData(0);
        baseActivity.requestOrderInfo();
    }

    @Override
    public void onLoadMore() {
        int number = tagPager.getNumber();
        //loadData(type, number + 1);
        loadData(number + 1);
    }

    public void updateViewStatus(RequestTag requestTag) {
        ptrFrameLayout.refreshComplete();
        if (tagPager.isLast()) {
            lvContent.noMore();
        } else {
            lvContent.stopLoadMore();
        }
    }



    private void initHeadView(View v) {
        ptrFrameLayout = (PtrFrameLayout) v.findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString("typeState", typeState);
        super.onSaveInstanceState(outState);
    }




    void loadData(int page){
/*        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd("buy/homepage/filters");
        RequestEntityMapSupply.putParameter("all", true);
        request(RequestEntityMapSupply, "buy/homepage/filters", onRequestListener);*/
        RequestEntitySupply<Map<String, String>> entity = new RequestEntitySupply<>();
        Map<String, String> map = new HashMap<>();
        map.put("agencyStoreId", BaseApplication.getInstance().getStoreId());

        map.put("pageNumber", page + "");
        map.put("pageSize", PAGE_SIZE + "");
        map.put("grouponStage", typeState);//+typeState);
        entity.setCmd("pm-order/baseorder/groupon/agencylist");
        entity.setParameters(map);
        RequestTag requestTag = new RequestTag();
        requestTag.tag = "pm-order/baseorder/groupon/agencylist";
        requestTag.action = page;

        requestTag.type = RequestTag.TYPE_CURRENT;
        request(entity, requestTag, onRequestListener);
    }

    OnRequestListener<ContentEntity<OrderAgentList>> onRequestListener = new OnRequestListener<ContentEntity<OrderAgentList>>() {
        @Override
        public ContentEntity<OrderAgentList> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<ContentEntity<OrderAgentList>>() {
            }.getType());
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.nostandingbook, "网络问题,请点击重试", HttpRequest.FAIL_NET_FAULT);
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (requestSucceedCount == 0){
                showExceptionView(R.mipmap.nostandingbook, arg + "", HttpRequest.FAIL_NET_FAULT);//arg + ",请点击重试"
            }
            RequestTag requestTag = (RequestTag) tag;
            updateViewStatus(requestTag);
        }

        @Override
        public void onStart(Object tag) {
            if (requestSucceedCount == 0 && !refreshFlag){
                showProgressView();
            }else
                refreshFlag = false;
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<OrderAgentList>> response, Object tag) {
            //页面第一次调用网络请求接口并成功
            showMainView();
            RequestTag requestTag = (RequestTag) tag;
            if (requestTag.action == 0||requestSucceedCount==0) {
                list.clear();
            }
            requestSucceedCount ++;

            ContentEntity<OrderAgentList> orderResponse = response.getResponseElement();
            List<OrderAgentList> content = orderResponse.getContent();
            tagPager.setLast(orderResponse.getLast());
            tagPager.setNumber(orderResponse.getNumber());
            tagPager.setSize(orderResponse.getSize());
            tagPager.setTotalElements(orderResponse.getTotalElements());
            list.addAll(content);
            adapter.notifyDataSetChanged();
            if(orderResponse.getNumber()==0){
                    lvContent.setSelection(0);
            }
            updateViewStatus(requestTag);
            if(list.size()==0){
                showExceptionView(R.mipmap.nostandingbook, "没有相关的代办订单", HttpRequest.FAIL_DATA_EMPTY);
            }
        }
    };



    public void showMainView() {
        vException.setVisibility(View.GONE);
        mainView.setVisibility(View.VISIBLE);
    }


    public void showExceptionView(int imgSrc, String text, int exceptionType) {
        if (imgSrc > 0) {

        }
        pb.setVisibility(View.GONE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.VISIBLE);
        ivExceptionIcon.setVisibility(View.VISIBLE);
        mainView.setVisibility(View.GONE);

        ivExceptionIcon.setImageResource(imgSrc);
        tvExceptionDescription.setText(text);
        tvExceptionDescription.setTag(exceptionType);
        ivExceptionIcon.setTag(exceptionType);
        tvExceptionDescription.setOnClickListener(this);
        ivExceptionIcon.setOnClickListener(this);
    }
    public void showProgressView() {

        pb.setVisibility(View.VISIBLE);
        vException.setVisibility(View.VISIBLE);
        tvExceptionDescription.setVisibility(View.GONE);
        ivExceptionIcon.setVisibility(View.GONE);
        mainView.setVisibility(View.GONE);
    }

    void requestCode(String id){
        RequestEntitySupply<Map<String, String>> entity = new RequestEntitySupply<>();
        Map<String, String> map = new HashMap<>();
        map.put("grouponId", id);
        entity.setCmd("pm-order/baseorder/groupon/inspectCode");
        entity.setParameters(map);
        RequestTag requestTag = new RequestTag();
        requestTag.tag = "pm-order/baseorder/groupon/inspectCode";
        request(entity, requestTag, onRequestCodeListener);
    }

    OnRequestListener<OrderAgentCode> onRequestCodeListener = new OnRequestListener<OrderAgentCode>() {
        @Override
        public OrderAgentCode jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, OrderAgentCode.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            T.toast("请求失败，请重试");
            hideProgressDialog();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            T.toast("请求失败，请重试");
            hideProgressDialog();

        }

        @Override
        public void onStart(Object tag) {
                //showProgressView();
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<OrderAgentCode> response, Object tag) {
            //页面第一次调用网络请求接口并成功
            hideProgressDialog();
            OrderAgentCode orderResponse = response.getResponseElement();
            showCodeDialog(orderResponse.getInspectCode());
        }
    };

    private Dialog dialogCancel;
    TextView[] numbers = new TextView[6];
    void showCodeDialog(String code){
        if (dialogCancel == null) {
            View view = LayoutInflater.from(context).inflate(R.layout.dialog_code, null);
            dialogCancel = new Dialog(context, R.style.ActionSheetDialogStyle);
            dialogCancel.setContentView(view);
            Window dialogWindow = dialogCancel.getWindow();
            if(dialogWindow==null)
                return;
            dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
            WindowManager.LayoutParams lp = dialogWindow.getAttributes();
            lp.width = LocalDisplay.SCREEN_WIDTH_PIXELS;
            dialogWindow.setAttributes(lp);
            numbers[0] = (TextView)view.findViewById(R.id.number1);
            numbers[1] = (TextView)view.findViewById(R.id.number2);
            numbers[2] = (TextView)view.findViewById(R.id.number3);
            numbers[3] = (TextView)view.findViewById(R.id.number4);
            numbers[4] = (TextView)view.findViewById(R.id.number5);
            numbers[5] = (TextView)view.findViewById(R.id.number6);
        }
        for(int i=0;i<6;i++){
            numbers[i].setText(""+code.charAt(i));
        }
        dialogCancel.show();
    }

}
